/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.nhc.activity_fragment;

import android.location.GpsSatellite;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.astrob.activitys.GPSProvider;
import com.astrob.model.LonLat;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.nhc.view.GPS2StarQDView;
import com.nhc.view.GPS2StarView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.util.TimeUtil;

/**
 * 使用方法：复制>粘贴>改名>改代码
 */

/**
 * fragment示例
 *
 * @use new DemoFragment(),具体参考.DemoFragmentActivity(initData方法内)
 */
public class SatelliteFragment extends BaseFragment implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "SatelliteFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static SatelliteFragment createInstance() {
        return new SatelliteFragment();
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (SysUtils.getInstance().is240x320) {
            setContentView(R.layout.satellite_fragment_240x320);
        } else {
            setContentView(R.layout.satellite_fragment);
        }

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private GPS2StarView mGpsView;
    private GPS2StarQDView mGPS2StarQDView;
    private TextView tvgpsnum_c;
    private TextView tvgpsaccuracy_c;
//    private TextView tv_gps;
//    private TextView tv_bds;
//    private TextView tv_glonss;
//    private TextView tv_s;
    private TextView tv_lon;
    private TextView tv_lat;
    private TextView tv_height;
    private TextView tv_vel;
    private TextView tv_localtime;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        mGpsView = (GPS2StarView) findViewById(R.id.view_gps_ephemeris);
        mGPS2StarQDView = (GPS2StarQDView) findViewById(R.id.view_gps_xz);

        tvgpsnum_c = (TextView) findViewById(R.id.tvgpsnum_c);
        tvgpsaccuracy_c = (TextView) findViewById(R.id.tvgpsaccuracy_c);
//        tv_gps = (TextView) findViewById(R.id.tv_gps);
//        tv_bds = (TextView) findViewById(R.id.tv_bds);
//        tv_glonss = (TextView) findViewById(R.id.tv_glonss);
//        tv_s = (TextView) findViewById(R.id.tv_s);
        tv_lon = (TextView) findViewById(R.id.tv_lon);
        tv_lat = (TextView) findViewById(R.id.tv_lat);
        tv_height = (TextView) findViewById(R.id.tv_height);

        tv_vel = (TextView) findViewById(R.id.tv_vel);
        tv_localtime = (TextView) findViewById(R.id.tv_localtime);

        tv_localtime.setText("-----");
        tvgpsaccuracy_c.setText("-----");
        tv_lat.setText("-----");
        tv_lon.setText("-----");
        tv_height.setText("");
        tv_vel.setText("-----");
    }

    private void clear() {
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
        count = 0;
    }


    private boolean isToStop = false;

    private void stopOrContinu() {
        isToStop = !isToStop;
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private GPSProvider mGpsProvider;

    @Override
    public void initData() {//必须在onCreateView方法内调用

        mGpsProvider = GPSProvider.getInstance();

    }

    private void refreshData() {
        int num = mGpsProvider.getGPSNum();

        if (num == 0) {
            tvgpsnum_c.setText(getCurGPSNum());
            tvgpsaccuracy_c.setText(" -----");
//            tv_gps.setText("0");
//            tv_bds.setText("0");
            tv_lat.setText(" -----");
            tv_lon.setText(" -----");
            tv_height.setText("");
            tv_vel.setText(" -----");

            mGpsView.postInvalidate();
            mGPS2StarQDView.postInvalidate();

            return;
        }

        tvgpsnum_c.setText(getCurGPSNum());
        tvgpsaccuracy_c.setText(getCurGPSAccuracy());
        tv_vel.setText(getCurGPSSpeed());

        ArrayList<GpsSatellite> gpsSatelliteList = mGpsProvider.getGpsSatellite();
        int gps = 0;
        int bd = 0;
        for (GpsSatellite g : gpsSatelliteList) {
            if (!g.usedInFix()) {
                continue;
            }
            if (g.getPrn() < 25) {
                gps++;
            } else {
                bd++;
            }
        }
//        tv_gps.setText(gps + "");
//        tv_bds.setText(bd + "");

        LonLat ll = null;
        if (mGpsProvider != null && mGpsProvider.isFixed()) {
            ll = mGpsProvider.getPos();
            tv_localtime.setText(getCurrentTime());
        }

        if (ll != null) {
            String strLL = SysUtils.getInstance().getLLStr(ll);
            String[] names = strLL.split("\n");
            if (names.length == 2) {
                tv_lat.setText(names[0]);
                tv_lon.setText(names[1]);
            }
        } else {
            tv_lat.setText(" -----");
            tv_lon.setText(" -----");
            tv_height.setText("");
            tv_vel.setText(" -----");
        }

        tv_height.setText(getCurGPSAltitude());
        mGpsView.postInvalidate();
        mGPS2StarQDView.postInvalidate();
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    @Override
    public void onTimerStart() {

    }

    private int count = 0;

    @Override
    public void onTimerRefresh() {
        if (isToStop == false) {
            count++;
            refreshData();
        }
    }

    @Override
    public void onTimerStop() {

    }

    @Override
    public void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    public void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    public String getCurGPSNum() {
        String strGPSNum = "-----";
        if (mGpsProvider != null && GPSProvider.getInstance().GetSatellite() != null) {
            Iterator<GpsSatellite> it = GPSProvider.getInstance().GetSatellite().iterator();
            int num = 0;
            int fixNum = 0;
            while (it.hasNext()) {
                GpsSatellite gpsState = it.next();
                if (gpsState.getSnr() > 0) {
                    num++;
                    if (gpsState.usedInFix())
                        fixNum++;
                }
            }
            if (num > 0) {
                strGPSNum = fixNum + " | " + num;
            }
        }

        return strGPSNum;
    }

    public String getCurGPSAccuracy() {
        String strAccuracy = "-----";
        if (mGpsProvider != null && mGpsProvider.isFixed()) {
            float accuracy = mGpsProvider.getAccuracy();
            if (accuracy < 100) {
                String SS[] = SysUtils.getInstance().getAltitudeStr(mGpsProvider.getAccuracy());
                strAccuracy = SS[0] + SS[1];
            }
        }

        return strAccuracy;
    }

    public String getCurGPSAltitude() {
        String strAltitude = "-----";
        if (mGpsProvider != null && mGpsProvider.isFixed()) {
            String SS[] = SysUtils.getInstance().getDistanceStr((int) mGpsProvider.getAltitude());
            strAltitude = SS[0] + SS[1];
        }

        return strAltitude;
    }

    public String getCurrentStatusText() {
        String strStatus = getResources().getString(R.string.gps_not_locate);
        if (mGpsProvider != null && mGpsProvider.isFixed()) {
            strStatus = getResources().getString(R.string.gps_located);
        }
        return strStatus;
    }

    public String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String strTime = formatter.format(curDate);
        return strTime;
    }

    public String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
        Date curDate = new Date(System.currentTimeMillis());
        String strDate = formatter.format(curDate);
        return strDate;
    }

    public String getCurGPSSpeed() {
        double speed = 0;//速度 米／秒
        if (GPSProvider.getInstance() != null && GPSProvider.getInstance().isFixed()) {
            speed = GPSProvider.getInstance().getSpeed();
        } else {
            speed = 0;
        }
        String VEL[] = SysUtils.getInstance().getVelStr(speed);
        return VEL[0] + VEL[1];
    }

    public String getDirection() {
        if (mGpsProvider == null)
            return null;

        double dDirection = 0;
        int DIRECT_STEP = 20;
        String strDir = null;

        dDirection = mGpsProvider.getDirection();

        if (dDirection <= DIRECT_STEP || dDirection >= 360 - DIRECT_STEP)
            strDir = getString(R.string.direct_north);
        else if (dDirection < 90 - DIRECT_STEP && dDirection > DIRECT_STEP)
            strDir = getString(R.string.direct_northeast);
        else if (dDirection <= 90 + DIRECT_STEP
                && dDirection >= 90 - DIRECT_STEP)
            strDir = getString(R.string.direct_east);
        else if (dDirection < 180 - DIRECT_STEP
                && dDirection > 90 + DIRECT_STEP)
            strDir = getString(R.string.direct_southeast);
        else if (dDirection <= 180 + DIRECT_STEP
                && dDirection >= 180 - DIRECT_STEP)
            strDir = getString(R.string.direct_south);
        else if (dDirection < 270 - DIRECT_STEP
                && dDirection > 180 + DIRECT_STEP)
            strDir = getString(R.string.direct_southwest);
        else if (dDirection <= 270 + DIRECT_STEP
                && dDirection >= 270 - DIRECT_STEP)
            strDir = getString(R.string.direct_west);
        else if (dDirection < 360 - DIRECT_STEP
                && dDirection > 270 + DIRECT_STEP)
            strDir = getString(R.string.direct_northwest);

        return strDir;
    }
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}